package main

import "log"

//bucket-token算法实现流量控制
//bucket:token,用channel来同步线程之间的信息

type ConnLimiter struct {
	concurrentConn int //并发连接个数
	bucket         chan int
}

func NewConnLimiter(cc int) *ConnLimiter {
	return &ConnLimiter{
		concurrentConn: cc,
		bucket:         make(chan int, cc),
		//buffer channel通过异步同步消息
	}
}

func (cl *ConnLimiter) GetConn() bool {
	//判断token是否已经拿到
	if len(cl.bucket) >= cl.concurrentConn {
		log.Printf("Reached the rate limitation.")
		return false
	}
	cl.bucket <- 1 //可以拿到一个token，传入1标志进管道
	return true
}

func (cl *ConnLimiter) ReleaseConn() {
	c := <-cl.bucket
	log.Printf("ReleaseConn success,New connection coming: %d", c)
}
